package top.zhangjianyong.blog.component;

import jakarta.mail.MessagingException;
import java.io.UnsupportedEncodingException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import top.zhangjianyong.blog.config.blog.BlogConfig;
import top.zhangjianyong.blog.constant.ThreadPoolConstant;

/**
 * 邮件工具组件
 *
 * @author zhangjianyong
 * @since 2024/7/19 下午8:16
 */
@Slf4j
@Component
public class MailSend {

  private final String fromEmailAccount;
  private final String fromEmailPassword;
  private final String fromEmailSMTPHost;

  public MailSend(BlogConfig blogConfig) {
    BlogConfig.Email email = blogConfig.getEmail();
    this.fromEmailAccount = email.getAccount();
    this.fromEmailPassword = email.getPassword();
    this.fromEmailSMTPHost = email.getSmtpHost();
  }

  public void send(String email, String mailSubject, String mailContext)
      throws MessagingException, UnsupportedEncodingException {
    Mail mail =
        new Mail(
            fromEmailAccount,
            fromEmailPassword,
            fromEmailSMTPHost,
            email,
            mailSubject,
            mailContext);
    mail.sendMail();
  }

  @Async(ThreadPoolConstant.ASYNC_V_CODE_EXECUTOR_BEAN)
  public void sendAsync(String email, String mailSubject, String mailContext) {
    try {
      send(email, mailSubject, mailContext);
    } catch (MessagingException | UnsupportedEncodingException e) {
      log.error(e.getMessage(), e);
    }
  }

  /**
   * 给自己发邮件
   *
   * @param mailSubject 邮件主题
   * @param mailContext 邮件内容
   */ 
  public void send(String mailSubject, String mailContext)
      throws MessagingException, UnsupportedEncodingException {
    send(fromEmailAccount, mailSubject, mailContext);
  }
}
